﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;

namespace FlashPay.Util
{
    /// <summary>
    /// 枚举工具
    /// </summary>
    /// <remarks>Immi 创建</remarks>
    public static class EnumUtil
    {
        private static Dictionary<string, IDictionary<int, string>> _enumList = new Dictionary<string, IDictionary<int, string>>();
        private static readonly object sync = new object();
        /// <summary>
        /// 枚举转换成字典
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <returns>字典</returns>
        /// <remarks>Immi 创建</remarks>
        public static IDictionary<int, string> ToDictionary(Type enumType)
        {
            string keyname = enumType.FullName;
            if (!_enumList.ContainsKey(keyname))
            {
                IDictionary<int, string> list = new Dictionary<int, string>();

                foreach (int i in Enum.GetValues(enumType))
                {
                    string name = Enum.GetName(enumType, i);

                    //取描述名称
                    string showName = string.Empty;
                    FieldInfo enumInfo = enumType.GetField(name);
                    var enumAttributes = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    showName = enumAttributes.Length > 0 ? enumAttributes[0].Description : name;

                    list.Add(i, showName);
                }

                if (!_enumList.ContainsKey(keyname))
                {
                    lock (sync)
                    {
                        _enumList.Add(keyname, list);
                    }
                }
            }
            return _enumList[keyname];
        }
    }
}
